const User = require('../models/user');
var http = require('http');
var querystring = require('querystring');
var bcrypt = require('bcrypt');
var SALT_WORK_FSCTOR = 10; // 计算强度,越大破解越困难
var simulation_login = require('./simulation-login');

//已登录
exports.layin = function (req, res) {
    console.log(req.session.user);
    var _user = req.session.user;
    res.send(_user);
};

//退出登录
exports.layout = function (req, res) {
    delete req.session.user;
    var _user = req.session.user;
    //delete app.locals.user; // 删除全局变量user,否则点击退出登录,页面无变化
    res.send(_user);
};

//注册
exports.Register = function (req, res) {
    var _user = req.body.user;
    var userName = _user.userName;
    var phone = _user.phone;
    console.log(_user.userName)
    User.findOne({ $or: [{ userName: userName }, { phone: phone }] },
        function (err, user) {
            if (err) {
                return console.log(err);
            }
            if (user) {
                return res.send('用户已存在');
            } else {
                var user = new User(_user);
                user.save(function (err, user) {
                    if (err) {
                        console.log(err);
                        return res.send('注册失败')
                    }
                    console.log('注册成功' + user);
                    return res.send('注册成功')
                });
            }
        });
};

////注册
exports.Sendmsg = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var params = req.body;
    console.log("params", params);
    /*var data='success'
    res.send(data);*/

    var code = "";
    for (var i = 0; i < 4; i++) {
        code += Math.floor(Math.random() * 10)
    }

    const getData = querystring.stringify({
        mobile: params.mobile,
        tpl_id: 46792,
        params: code,
        sign: 'API无忧',
        token: params.token
    });
    var opt = {
        hostname: 'www.api51.cn',
        path: '/api/smsApi/sendcode',
        method: 'POST',
        headers: {                      //post请求需要设置headers
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(getData)
        }
    }
    var sendmsg = ''
    const request = http.request(opt, function (response) {
        response.on("data", function (chuck) {
            sendmsg += chuck;
        });
        response.on("end", function () {
            var list = JSON.parse(sendmsg)
            console.log(list);
            res.send(code);
        });
    });
    request.on('error', function (e) {
        console.error('请求遇到问题:' + e.message);
    });
    request.write(getData);
    request.end();

};

//登录
exports.login = function (req, res) {
    var _user = req.body.user;
    var userName = _user.userName;
    var password = _user.password;

    User.findOne({ userName: userName }, function (err, user) {
        if (err) {
            return console.log(err);
        }
        if (!user) {
            return res.send('用户不存在');
        }
        if (user) {
            user.comparePassword(password, function (err, isMatch) {
                if (err) {
                    return console.log(err);
                }
                if (isMatch) {
                    req.session.user = user; // 用户名存入session中
                    console.log('登录成功' + user);
                    return res.send('登录成功')
                } else {
                    console.log('登录失败');
                    return res.send('登录失败')
                }
            });
        }

    });

};

//忘记密码，信息匹配，更新密码
exports.findPsw = function (req, res) {
    var _user = req.body.NewForm;
    var userName = _user.userName;
    var phone = _user.phone;
    var _password = _user.password;

    bcrypt.genSalt(SALT_WORK_FSCTOR, function (err, salt) {
        if (err) {
            return next(err);
        }

        bcrypt.hash(_password, salt, function (err, hash) {
            if (err) {
                return next(err);
            }

            _password = hash;
            User.findOne({ userName: userName, phone: phone }, function (err, result) {
                if (err) {
                    return console.log(err);
                }
                if (!result) {
                    console.log('信息错误');
                    return res.send('信息错误');
                }
                if (result) {
                    User.update({ userName: userName }, { "$set": { password: _password } }, function (err, user) {
                        if (err) {
                            return console.log(err);
                        }
                        if (user) {
                            console.log('新密码设置成功');
                            return res.send('新密码设置成功');
                        } else {
                            console.log('新密码设置失败');
                            return res.send('信息错误');
                        }
                    })
                }
            });

        })
    });
};
//获取用户信息
exports.getUserMsg = function (req, res) {
    var _user = req.session.user;
    var userName = _user.userName;

    User.findOne({ userName: userName }, function (err, user) {
        if (err) {
            return console.log(err);
        }
        if (user) {
            console.log(user);
            return res.send(user)
        } else {
            return console.log(err);
        }
    })
};
//修改用户信息
//修改昵称
exports.resetName = function (req, res) {
    var name = req.body.name;
    var _user = req.session.user;
    var userName = _user.userName;

    User.update({ userName: userName }, { '$set': { name: name, updateAt: Date.now() } }, function (err, user) {
        if (err) {
            return console.log(err);
        }
        if (user) {
            console.log('修改成功');
            return res.send('修改成功');
        } else {
            console.log(err);
        }
    });
};
//修改手机号
//exports.resetPhone = function (req,res) {
//   var phone = req.body.phone; 
//    var _user = req.session.user;
//    var userName = _user.userName;

//    User.update({userName:userName},{'$set':{phone:phone,updateAt:Date.now()}},function(err,user){
//        if(err){
//            return console.log(err);
//       }
//       if(user){
//            console.log('修改成功');
//            return res.send('修改成功');
//       }else{
/*    console.log(err); */
/*         }
    }); */
//};
//修改邮箱
//exports.resetEmail = function (req,res) {
//   var email = req.body.email; 
//    var _user = req.session.user;
//    var userName = _user.userName;

//    User.update({userName:userName},{'$set':{email:email,updateAt:Date.now()}},function(err,user){
//        if(err){
//            return console.log(err);
//       }
//        if(user){
//            console.log('修改成功');
//           return res.send('修改成功');
//       }else{
//           console.log(err);
//       }
//   });
//};
// //学生认证
exports.checkStu = function (req, res) {
    var _student = req.body.student;
    var userName = _student.userName;
    var password = _student.password;

    User.findOne({ "student.number": userName }, function (err, result) {
        if (err) {
            return console.log(err);
        }
        if (result) {
            return res.send("学生认证失败");
        } else if (!result) {
            new simulation_login(userName, password).getStudentMessage().then(Data => {
                if (Data.code === 0) {
                    _number = Data.student.number;
                    _name = Data.student.name;
                    _grad = Data.student.grad;
                    _major = Data.student.major;
                    _email = Data.student.email;
                    _avatar = Data.student.avatar;
                    _teacher = Data.student.teacher;
                    _assistant = Data.student.assistant

                    _user = req.session.user
                    id = _user._id

                    User.update({ _id: id }, {
                        '$set': {
                            checkStudent: "1", student: {
                                number: _number, 
                                name: _name, 
                                grad: _grad, 
                                major: _major, 
                                email: _email, 
                                avatar: _avatar, 
                                teacher: _teacher,
                                assistant: _assistant
                            }
                        }
                    }, function (err, user) {
                        if (err) {
                            return console.log(err);
                        }
                        if (user) {
                            delete req.session.user;
                            console.log("学生认证成功");
                            return res.send("学生认证成功");
                        } else {
                            console.log("学生认证失败");
                            return res.send("学生认证失败");
                        }
                    })

                } else if (Data.code === -1) {
                    console.log("学生信息有误");
                    return res.send("学生认证失败");
                }
            })
        }
    })
}
//用户管理 查找总条数
// exports.loadAll=function(req,res){
//     let grade=req.body.grade
//     if(grade==''){
//         User.find({checkStudent:0,role:10},function(err,result){
//             if(err){
//                 return console.log(err)
//             }
//             if(result){
//                 res.send(result);
//             }
//         })
//     }else{
//         User.find({"student.grad":grade},function(err,result){
//             if(err){
//                 return console.log(err)
//             }
//             if(result){
//                 //console.log(result);
//                  res.send(result);
//             }
//         })
//     } 
// }
//用户管理，按年级查找分类
// exports.category =function(req,res){
//     let grade=req.body.grade;
//     let pageSize = 5                   //一页多少条
//     let currentPage = req.body.page;                //当前第几页）
//     let skipnum = (currentPage - 1) * pageSize;   //跳过数

//     if(grade==''){
//         User.find({checkStudent:0,role:10}).skip(skipnum).sort({_id:-1}).limit(pageSize).exec(function(err1,result1){
//             if(err1){
//                 return console.log(err1)
//             }
//             if(result1){
//                 console.log();
//                 return res.send(result1);
//             }
//         })
//     }else{
//         User.find({"student.grad":grade,role:10}).skip(skipnum).sort({"student.number":1}).limit(pageSize).exec(function(err,result){
//             if(err){
//                 return console.log(err)
//             }
//             if(result){
//                 //console.log(result);
//                 return res.send(result);
//             }
//         })
//     } 
// }

// exports.Udelete =function(req,res){
//     let id =req.body.delId
//     if(id){
//         User.remove({_id:id},function(err,delResult){
//             if(err){
//                 return console.log(err)
//             }else{
//                 console.log("删除用户成功");
//                 res.send('删除用户成功')
//             }
//         })
//     }
// }
//midware for user 中间件
//登录判断
exports.checkLogin = function (req, res) {
    var user = req.session.user

    if (!user) {
        return res.send('未登录')
    } else {
        res.send(user)
    }
}
//学生认证判断
exports.StuRequired = function (req, res) {
    var user = req.session.user

    if (user.checkStudent === 1) {
        res.send('ok');
    } else {
        return res.send('未认证')
    }
}
// //用户权限判断
// exports.adminRequired = function(req,res){
//     var user = req.session.user

//     if(user.role <= 10){
//         return res.send('没有权限')
//     }
//     res.send('ok');
// }
